﻿using DevComponents.DotNetBar.Controls;
using Model;
using Model.Enum;
using MQTTTool.Controls;
using MQTTTool.Util;
using SerailDriver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQTTTool.Page.Com
{

    public partial class AutoMsgForm : Form
    {

        static string Mqttcompageename = "Mqtt.save.taoke";
        public SerailDriverCla serailDriver;
        List<AutoMsgModel> models;
        public AutoMsgForm()
        {
        }
        public AutoMsgForm(List<AutoMsgModel> models)
        {
            
            InitializeComponent();
            this.models = models;
           // serailDriver.automsg += getModels;
            GetModels();
            //SerailDriverCla se = new SerailDriverCla(models);
            //getModels();
            InitModels();
            
        }
        /// <summary>
        /// 加载models进表格，注意区分16进制
        /// </summary>
        private void InitModels()
        {
            List<AutoMsgModel> modelDataList = this.models;
           
            DataGridViewX dataGridViewX = this.dataGridViewX1;
            if (modelDataList!=null)
            {
                for (int i = 0; i < modelDataList.Count; i++)
                {
                    Boolean bo16 = modelDataList[i].b16;
                    if (bo16)
                    {

                        //获取存储数据收到的信息
                        List<byte> ReceverByteList = modelDataList[i].ReceverMsg;
                        byte [] byteData = ReceverByteList.ToArray();
                        //byte字节转换字符串
                        string ReceverMsg = Encoding.UTF8.GetString(byteData);
                        //字符串转16进制
                        string str =  stringToHex(ReceverMsg);

                        //获取存储数据收到的信息
                        List<byte> SendMsgByteList = modelDataList[i].SendMsg;
                        byte[] SendMsgData = SendMsgByteList.ToArray();
                        //byte字节转换字符串
                        string SendMsg = Encoding.UTF8.GetString(SendMsgData);
                        //字符串转16进制
                        string SendMsgStr = stringToHex(SendMsg);
                        dataGridViewX.Rows.Add(str, SendMsgStr, modelDataList[i].b16, modelDataList[i].Using);
                       /* dataGridViewX.Rows[i].Cells[0].Value = str;
                        dataGridViewX.Rows[i].Cells[1].Value = SendMsgStr;
                        dataGridViewX.Rows[i].Cells[2].Value = modelDataList[i].b16;
                        dataGridViewX.Rows[i].Cells[3].Value = modelDataList[i].Using;*/
                        /*dataGridViewX.Rows[i].Cells[2].Value = modelDataList[i];*/
                    }
                    else
                    {
                        //byte字节转换字符串  
                        List<byte> ReceverByteList = modelDataList[i].ReceverMsg;
                        byte[] byteData = ReceverByteList.ToArray();
                        List<byte> SendMsgByteList = modelDataList[i].SendMsg;
                        byte[] sreceve = SendMsgByteList.ToArray();
                           

                        string recever = Encoding.UTF8.GetString(byteData);
                        string send = Encoding.UTF8.GetString(sreceve);
                        dataGridViewX.Rows.Add(recever, send, modelDataList[i].b16, modelDataList[i].Using);
                        /*dataGridViewX.Rows[i].Cells[0].Value = recever;
                        dataGridViewX.Rows[i].Cells[1].Value = send;
                        dataGridViewX.Rows[i].Cells[2].Value = modelDataList[i].b16;
                        dataGridViewX.Rows[i].Cells[3].Value = modelDataList[i].Using;*/
                    }
                }
            }
            
           

        }
        /// <summary>
        /// 从表格中获取models。注意区分16进制
        /// </summary>
        public List<AutoMsgModel> GetModels()
        {
            return addModelData();
        }


        public void getModels()
        {
            GetModels();
        }

        /// <summary>
        /// 添加一行数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click(object sender, EventArgs e)
        {
            this.dataGridViewX1.Rows.Add("", "", false, false, "");
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private string stringToHex(string str)
        {
            //转换成16进制格式
            //bool checkBoxX_16= checkBoxX_16.
            Encoding encode = new UTF8Encoding();
            string rich = str;
            /*  if ((rich.Length % 2) != 0)
              {
                  rich += " ";//空格
                           //throw new ArgumentException("s is not valid chinese string!");
              }*/

            System.Text.Encoding chs = System.Text.Encoding.UTF8;//GetEncoding("GB2312");

            byte[] bytes = chs.GetBytes(rich);

            string msg = "";

            for (int i = 0; i < bytes.Length; i++)
            {
                msg += (string.Format("{0:X}", bytes[i]) + " ");
            }

            return msg;

        }
        private string stringtotex1(string str)
        {
            /*************** 将 16进制字符串 解码成 字符串 ***************/
            // richTextBoxEx2.Text = DecodeHexadecimalToStr(richTextBoxEx2.Text);
            //  (System.Text.Encoding.GetEncoding("gb23122")).GetString("wdaea");
            string rich = str;
         
            List<Object> bytes = rich.Split(' ').Select<string, Object>(text =>
            {
                try
                {
                    return Convert.ToByte(text, 16);

                }
                catch (Exception)
                {

                    return "";
                }
            }).ToList<Object>();
            bytes.RemoveAll(item => item == "");
            byte[] blist = bytes.Select<object, byte>(item =>
            {
                return (byte)item;

            }).ToArray();
            // 获得 GB2312，Chinese Simplified。
            Encoding chs = System.Text.Encoding.UTF8;//GetEncoding("GB2312");
            str = chs.GetString(blist);
            return str;
        }


        //保存自动回复窗口的信息
        private List<AutoMsgModel> addModelData()
        {
            DataGridViewRowCollection getRowsData = this.dataGridViewX1.Rows;//拿全部行的数据
            /*List<Object> list = a;*/

            //Hashtable hashtable = new Hashtable();
            List<AutoMsgModel> modelList = new List<AutoMsgModel>();
            for (int i = 0; i < getRowsData.Count; i++)
            {
                AutoMsgModel auto = new AutoMsgModel();
                DataGridViewRow list = getRowsData[i];
                string access = list.AccessibilityObject.Value;
                string[] dataList = access.Split(';');

                //c.Substring(0,)
                if (dataList[0] != string.Empty && dataList[0] != " " && dataList[0] != "(新建)") //判断保存的行不为空
                {
                    //hashtable.Add(split[0], split[1]);

                    if (dataList[2] == "(null)")
                    {
                        dataList[2] = "false";
                    }
                    if (dataList[3] == "(null)")
                    {
                        dataList[3] = "false";
                    }

                    auto.b16 = Convert.ToBoolean(dataList[2]);
                    auto.Using = Convert.ToBoolean(dataList[3]);

                    auto.ReceverMsg = Encoding.UTF8.GetBytes(dataList[0]).ToList();
                    auto.SendMsg = Encoding.UTF8.GetBytes(dataList[1]).ToList();
                    modelList.Add(auto);//保存当前窗口自动回复信息
                    

                    //string a= stringToHex(dataList[0]);
                }
            }
            AutoUtil.AutoMsgModel = modelList;
            return modelList;
            //关闭当前窗口
            /*this.DialogResult = DialogResult.OK;*/
        }


        private void buttonX2_Click(object sender, EventArgs e)
        {
            /*		DataGridViewRowCollection a = this.dataGridViewX1.Rows;//拿全部行的数据
                    *//*List<Object> list = a;*//*

                    Hashtable ht = new Hashtable();
                    AutoMsgModel auto = new AutoMsgModel();
                    for (int i = 0; i<a.Count;i++)
                    {
                        DataGridViewRow list = a[i];
                        String c = list.AccessibilityObject.Value;
                        String[] w = c.Split(';');
                        //c.Substring(0,)
                        if (w[0] != string.Empty && w[0] != " " && w[0] != "(新建)") //判断保存的行不为空
                        {
                            ht.Add(w[0], w[1]);
                        }
                    }*/

            this.models = addModelData();
            Console.WriteLine("保存成功！");
            Console.WriteLine(this.models);
            Console.ReadLine();

            this.DialogResult = DialogResult.OK;
        }
        int intex = 0;
        private void dataGridViewX1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
             
            
            int rowindex = e.RowIndex;//点击第几行
            int columnindex= e.ColumnIndex;//第几列的值
                                           //string bo = dataGridViewX1.SelectedRows[a].Cells[c].Value;
                                           // string name = this.dataGridViewX1.SelectedRows;
            string receive = "";
            string postback = "";

            if (columnindex == 2)
            {
                //string name = this.dataGridViewX.SelectedRows(e.RowIndex).Cells(c).Value.ToString();
                /*object bo = dataGridViewX1.SelectedRows[a].Cells[c].Value;*/
                //string name = this.dataGridViewX1.SelectedRows;
                string getRowsData = this.dataGridViewX1.Rows[rowindex].Cells[columnindex].EditedFormattedValue.ToString();
                if (getRowsData!=null && getRowsData=="False")
                {
                    receive= stringToHex(this.dataGridViewX1.Rows[rowindex].Cells[0].Value.ToString());//收到的信息转16进制
                    postback = stringToHex(this.dataGridViewX1.Rows[rowindex].Cells[1].Value.ToString());//回发的信息转16进制
                    dataGridViewX1.Rows[rowindex].Cells[0].Value = receive;
                    dataGridViewX1.Rows[rowindex].Cells[1].Value = postback;
                }
                else if(getRowsData != null && getRowsData == "True")
                {
                    receive = stringtotex1(this.dataGridViewX1.Rows[rowindex].Cells[0].Value.ToString());//收到的信息转字符串
                    postback = stringtotex1(this.dataGridViewX1.Rows[rowindex].Cells[1].Value.ToString());//回发的信息转字符串
                    dataGridViewX1.Rows[rowindex].Cells[0].Value = receive;
                    dataGridViewX1.Rows[rowindex].Cells[1].Value = postback;
                }
            }
            
            
            if (columnindex==4) {
                /*for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
                {*/
                intex++;

                

                if(intex == 2)
                {
                    intex = 0;
                }
                else
                {
                    DataGridViewRow row = dataGridViewX1.Rows[rowindex];
                    this.dataGridViewX1.Rows.Remove(row);
                }
                /*i--;*/
            }
           /* }*/
        }
        /*public void autoresponse(string richtext,ComPage com)
        {

            List<AutoMsgModel> modelDataList = this.models;
            string richTextBoxex1 = richtext;
            int start = 23, length = 5;
            string sub = richTextBoxex1.Substring(start - 1, length);
            string sub1 = richTextBoxex1.Substring(29-1);


            if (sub.Trim().Equals("收到消息"))
            {
                

                DataGridViewX dataGridViewX = this.dataGridViewX1;
                if (modelDataList != null)
                {
                    for (int i = 0; i < modelDataList.Count; i++)
                    {

                            //获取存储数据收到的信息
                         
                            //获取存储数据收到的信息

                            bool us = modelDataList[i].Using;
                        if (us==true)
                        {
                            //字节转字符串
                            List<byte> rece = modelDataList[i].ReceverMsg; //收到信息
                            byte[] sreceve = rece.ToArray();
                            List<byte> SendMsgByteList = modelDataList[i].SendMsg;//回复信息
                            byte[] SendMsgData = SendMsgByteList.ToArray();
                            string send = Encoding.UTF8.GetString(SendMsgData);//回复信息
                            string recever = Encoding.UTF8.GetString(sreceve);//收到信息
                            if (sub1.Trim().Equals(recever))
                            {
                               
                              com.AddLog("自动回复:" + send, LogEnum.SendLog);

                            }
                        }                      
                    }
                }
            }
        }*/
    }
}
